import {Component, HostBinding, OnInit} from '@angular/core';
import {UserService} from '../../service/user.service';
import {MatDialog, MatSnackBar} from '@angular/material';
import {ConfigService} from '../../service/config.service';
import {defaultRouteAnim} from '../../anim/router.anim';
import {errorSnackBar, openSnackBar} from '../../util/snack.util';
import {loadingDialog} from '../../util/dialog.util';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  animations: [defaultRouteAnim]
})
export class HomeComponent implements OnInit {
  @HostBinding('@routeAnim') routeAnim;
  isSigned = false;

  constructor(
    private snackBar: MatSnackBar, private dialog: MatDialog,
    public userService: UserService, public configService: ConfigService) {
  }

  ngOnInit() {
    // 更新用户信息
    this.userService.get().subscribe((user) => {
      this.userService.userChangeEvent.emit(user);
      this.isSigned = this.userService.user.isSigned;
    }, error1 => {
      errorSnackBar(this.snackBar, error1);
    });
    // 获取公告
    if (!this.configService.noticeArray) {
      this.configService.getNotice(this.userService.user.token).subscribe(noticeArray => {
        this.configService.noticeArray = [];
        for (const notice of noticeArray) {
          const create = new Date(notice.created);
          const modify = new Date(notice.modify);
          notice.message = `${notice.message}
          \n\n发布于: **${create.toLocaleDateString()} ${create.toLocaleTimeString()}**
          \n\n最后更新: **${modify.toLocaleDateString()} ${modify.toLocaleTimeString()}**`;
          this.configService.noticeArray.push(notice);
        }
      }, error1 => {
        errorSnackBar(this.snackBar, error1);
      });
    }
  }

  signed() {
    const loadingDialogRef = loadingDialog(this.dialog);
    this.userService.signed().subscribe(sign => {
      loadingDialogRef.close();
      this.isSigned = true;
      openSnackBar(this.snackBar, '签到成功，本月连续签到: ' + sign.continueSignMonth + '天，经验 +' + sign.exp);
    }, error1 => {
      loadingDialogRef.close();
      errorSnackBar(this.snackBar, error1);
    });
  }
}
